package com.vrv.im.control;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hangutech.excel.ExcelAccessor;
import com.hangutech.excel.ExcelAccessorImpl;
import com.hangutech.excel.ExcelProcessResult;
import com.hangutech.excel.comfig.SheetMappingConfig;
import com.hangutech.excel.comfig.SheetMappingParser;
import com.vrv.im.domain.ProjectBean;
import com.vrv.im.domain.UserBean;
import com.vrv.im.service.ProjectService;
import com.vrv.im.service.UserRoleService;
import com.vrv.im.service.UserService;
import com.vrv.im.util.Constant;
import com.vrv.im.vo.ExcelUploadVo;
import com.vrv.im.vo.UserVo;

@Controller
@RequestMapping("/upload")
public class UploadController {
	@Autowired
	private UserService userService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private UserRoleService userRoleService;

	@RequestMapping("/goToPage")
	public ModelAndView gotoPage(@ModelAttribute("voModel") UserBean ub) {
		if (ub == null || !StringUtils.hasText(ub.getOpenId())
                || !StringUtils.hasText(ub.getToken())) {
            ModelAndView mav = new ModelAndView("userbind/bind");
            mav.addObject("voModel", new UserBean());
            mav.addObject("type", "error");
            mav.addObject("errotMsg", "请传递参数openID，tocken");
            return mav;
        }
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id", ub.getId());
		map.put("openId", ub.getOpenId());
		map.put("token", ub.getToken());
		return new ModelAndView("/upload/add",map);
	}

	@RequestMapping("/add")
	public ModelAndView add(@RequestParam("file") MultipartFile file,@ModelAttribute("voModel") UserBean ub) {
		if (ub == null || !StringUtils.hasText(ub.getOpenId())
                || !StringUtils.hasText(ub.getToken())) {
            ModelAndView mav = new ModelAndView("userbind/bind");
            mav.addObject("voModel", new UserBean());
            mav.addObject("type", "error");
            mav.addObject("errotMsg", "请传递参数openID，tocken");
            return mav;
        }
		List<UserVo> userList = new ArrayList<UserVo>();

		SheetMappingParser parser = new SheetMappingParser();
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		URL url = classLoader.getResource("excel/ExcelMap.xml");
		SheetMappingConfig mappingConfig = parser.parse(url);
		ExcelAccessor excelHelper = new ExcelAccessorImpl(mappingConfig);
		ExcelProcessResult excelProcessResult;
		try {
			excelProcessResult = excelHelper.read(file.getInputStream(), file.getOriginalFilename());
			if (excelProcessResult.isSuccess()) {
				@SuppressWarnings("unchecked")
				List<ExcelUploadVo> list = (List<ExcelUploadVo>) excelProcessResult.getResultObject();
				if (list != null && list.size() > 0) {
					for (ExcelUploadVo v : list) {
						ProjectBean pro = new ProjectBean();
						pro.setContractNum(v.getContractNum());
						pro.setEndTime(v.getEndTime().getTime());
						pro.setBeginTime(v.getBeginTime().getTime());
						pro.setArea(v.getArea());
						pro.setCommunityName(v.getCommunityName());
						pro.setCommunityNum(v.getCommunityNum());
						pro.setAddress(v.getAddress());
						pro.setWorkType(v.getWorkType());

						UserVo ower = new UserVo();
						ower.setName(v.getOwnerName());
						ower.setPhone(v.getOwnerPhone());
						ower.setToken(v.getOwnerTokenID());
						ower.setRoleMark(Constant.OWNER_ROLE_ID);
						ower.setOpenId(ub.getOpenId());
						userList.add(ower);

						UserVo designer = new UserVo();
						designer.setName(v.getDesignerName());
						designer.setPhone(v.getDesignerPhone());
						designer.setToken(v.getDesignerTokenID());
						designer.setRoleMark(Constant.DESIGNER_ROLE_ID);
						designer.setOpenId(ub.getOpenId());
						userList.add(designer);

						UserVo shopp = new UserVo();
						shopp.setName(v.getShoppingName());
						shopp.setPhone(v.getShoppingPhone());
						shopp.setToken(v.getShoppingTokenID());
						shopp.setRoleMark(Constant.SHOPPING_ROLE_ID);
						shopp.setOpenId(ub.getOpenId());
						userList.add(shopp);

						UserVo lead = new UserVo();
						lead.setName(v.getManagerName());
						lead.setPhone(v.getManagerPhone());
						lead.setToken(v.getManagerTokenID());
						lead.setRoleMark(Constant.LEADER_ROLE_ID);
						lead.setOpenId(ub.getOpenId());
						userList.add(lead);

						UserVo supervisor = new UserVo();
						supervisor.setName(v.getSupervisorName());
						supervisor.setPhone(v.getSupervisorPhone());
						supervisor.setToken(v.getSupervisorTokenID());
						supervisor.setRoleMark(Constant.SUPERVISOR_ROLE_ID);
						supervisor.setOpenId(ub.getOpenId());
						userList.add(supervisor);

						UserVo backup = new UserVo();
						backup.setName(v.getBackupName());
						backup.setPhone(v.getBackupPhone());
						backup.setToken(v.getBackupTokenID());
						backup.setRoleMark(Constant.BACKUP_ROLE_ID);
						backup.setOpenId(ub.getOpenId());
						userList.add(backup);

						Map<Long, Long> map = userService.addListUser(userList);
						if (map != null && map.size() > 0) {
							// 添加项目
							pro.setOwnerID(map.get(Constant.OWNER_ROLE_ID));
							pro.setDesignerID(map.get(Constant.DESIGNER_ROLE_ID));
							pro.setShoppingID(map.get(Constant.SHOPPING_ROLE_ID));
							pro.setManagerID(map.get(Constant.LEADER_ROLE_ID));
							pro.setSupervisorID(map.get(Constant.SUPERVISOR_ROLE_ID));
							pro.setBackupID(map.get(Constant.BACKUP_ROLE_ID));
							long projectID = projectService.addProject(pro);
							userRoleService.addRelation(projectID, map);
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ModelAndView("/upload/result");
	}
	@RequestMapping("/down")
	public ModelAndView exportSample(HttpServletResponse response,@ModelAttribute("voModel") UserBean ub){
		if (ub == null || !StringUtils.hasText(ub.getOpenId())
                || !StringUtils.hasText(ub.getToken())) {
            ModelAndView mav = new ModelAndView("userbind/bind");
            mav.addObject("voModel", new UserBean());
            mav.addObject("type", "error");
            mav.addObject("errotMsg", "请传递参数openID，tocken");
            return mav;
        }
	      try {
	      OutputStream os = response.getOutputStream(); 
          // 输入流对象
	      String name=this.getClass().getClassLoader().getResource("template/Sample.xls").getFile();
	      FileInputStream ins = new FileInputStream(name);
          String uploadFileName = "导入模板.xls";
          response.setHeader("Content-Disposition", "attachment;filename=" + new String(uploadFileName.getBytes("GBK"), "iso8859-1"));
          response.setContentType("application/vnd.ms-excel;charset=UTF-8");
          byte[] buff = new byte[2048];    
          int bytesRead;    
          while (-1 != (bytesRead = ins.read(buff, 0, buff.length))) {    
        	  os.write(buff, 0, bytesRead);    
          } 
          if (response != null) {
              if (response.getOutputStream() != null)
                  response.getOutputStream().flush();
              if (response.getOutputStream() != null)
                  response.getOutputStream().close();
              if(ins!=null)
            	  ins.close();
          }
      } catch (Exception e) {
      	e.printStackTrace();
      }
		return null;
	}
}
